package net.media.datafw.transport.mvc;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.media.datafw.model.ResponseModel;
import net.media.datafw.utils.ReadUtil;

import org.springframework.web.servlet.View;

public class TransportView implements View {

	public static final String HEADER_TRANSPORT_VIEW_RESPONSE_CODE = "X-Data-ResponseCode";
	public static final String HEADER_TRANSPORT_VIEW_RESPONSE_MESSAGE = "X-Data-ResponseMessage";

	public static final String TRANSPORT_VIEW_RESPONSE_DATA = "responseData";
	public static final String TRANSPORT_VIEW_RESPONSE_CODE = "responseCode";
	public static final String TRANSPORT_VIEW_RESPONSE_MESSAGE = "responseMessage";

	public static final int TRANSPORT_VIEW_RESPONSE_CODE_SUCCESS = 0;
	public static final int TRANSPORT_VIEW_RESPONSE_CODE_FAILURE = 1;

	public static final String TRANSPORT_VIEW_RESPONSE_MESSAGE_SUCCESS = "Success";
	public static final String TRANSPORT_VIEW_RESPONSE_MESSAGE_UNKNOWN = "Unknown error Occured";
	public static final String TRANSPORT_VIEW_RESPONSE_MESSAGE_NOT_TRANSPORTABLE = "Invalid Non Tranportable Object";

	public static final String PARAM_REQUEST_TYPE = "req_type";
	public static final String PARAM_RESPONSE_TYPE = "res_type";

	public static final String PROP_MODEL = "response";

	private TransportType transportType = null;

	public TransportView() {
	}

	public String getContentType() {
		return (this.transportType != null) ? this.transportType.getContentType() : null;
	}

	public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
		this.transportType = TransportType.getTransportType(ReadUtil.getInt(request.getParameter(PARAM_RESPONSE_TYPE), 0));
		ResponseModel responseData = (ResponseModel) model.get(PROP_MODEL);
		int responseCode = responseData.getResponseCode();
		String responseMessage = responseData.getResponseMessage();
		byte[] data = (this.transportType.getTransporter()).serialize(responseData);
		response.setHeader(HEADER_TRANSPORT_VIEW_RESPONSE_CODE, String.valueOf(responseCode));
		response.setHeader(HEADER_TRANSPORT_VIEW_RESPONSE_MESSAGE, responseMessage);
		response.getOutputStream().write(data);
	}
}
